/*
 * axios全局配置
 */
import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'

const instance = axios.create({
  baseURL:"http://api.52pp365.com/",
  timeout: 40000
})

//配置请求拦截器
instance.interceptors.request.use(
  config => {
    //从redux中获取之前保存的token
    const token = window.localStorage.getItem('h5_token')
    if (token) {
      //如果token存在，就设置到请求头中
      config.headers.token = `${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

//配置响应拦截器
instance.interceptors.response.use(response => {
  if (response.data.flag === 1) {
    return response.data
  } else if (response.data.flag === 9000) {
    window.localStorage.removeItem('h5_token')
    window.location.reload()
  } else {
    Toast.fail(`${response.data.message}`)
    return
  }
})

export const getRequest = (url = '', data = {}) => {
  if (qs.stringify(data)) {
    url += url.includes('?') ? '&' + qs.stringify(data) : '?' + qs.stringify(data)
  }
  return instance.get(url)
}

export const postRequest = (url = '', data = {}) => {
  return instance.post(url, data)
}
